const api = require('../../utils/api.js')
const MSG = require('../../utils/util.js')
const app = getApp()
var timeout;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 显示注册按钮
    phone: wx.getStorageSync('phone'),
    showTexarea: false,
    radioItems: [{
        name: '余额支付',
        value: '0',
        icon: '/images/cashpay.png'
      },
      {
        name: '微信支付',
        value: '1',
        icon: '/images/wepay.png'
      },
    ],
    fixedBtnHeight: '',
    amount: '',
    shopName: '',
    discount: 10,
    userLevelName: '',
    balance: '',
    userId: wx.getStorageSync('user').userId,
    couponNumber: '', // 可用优惠券张数
    Length: 4,
    leftOffset: '',
    isFocus: true,
    Value: "",
    discountMoney: ' ', // 优惠金额 
    choseCard: true, // 选择会员卡优惠
    couponDiscount: '',
    needPay: 0, // 还需要支付
    smsConfirm: false,
    isWePay: false, // 是否微信支付
    wxCard: '', // 是否有微信卡号
    noNet: false, // 没有网络
    minAmount: '', // 起用金额
    maxAmount: '', // 最高金额
    vipDiscount: '', // 会员卡折扣金额
    remark: '', // 备注
    remarkLength: 0, // 留言长度
    payFormId: '', // 金额的formid
    disType: '', // 优惠券类型
    isYLPay: false,
    mobileGrant: '', // 是否需要手机号授权
    conMT: '440rpx'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setStorageSync('couponDiscount', '');
    wx.setStorageSync('minAmount', '');
    wx.setStorageSync('maxAmount', '');
    var that = this;
   
    if(app.globalData.mobileGrant && app.globalData.mobileGrant !=''){
      console.log(111)
      this.setData({
        mobileGrant: app.globalData.mobileGrant
      })
      if(app.globalData.mobileGrant === 0){
        that.getUserDetal(app.globalData.userId)
        that.setData({
          phone: app.globalData.mobile ||'',
          conMT: '60rpx'
        })
      }
      api.post('shop/getShop',{
        shopId: app.globalData.shopId,
        userId: app.globalData.userId
      }).then(response =>{
        if(response.data.success){
          that.setData({
          shopName :response.data.data.shopName,

          })    
        }
      })
    }else{
      app.userInfoCallback = (res => { 
        that.setData({
          mobileGrant: res.data.data.mobileGrant
        })
        if(res.data.data.mobileGrant === 0){
          that.getUserDetal(res.data.data.userId)
          that.setData({
            phone: res.data.data.mobile|| '',
            conMT: '60rpx'
          })
        }
        api.post('shop/getShop',{
          shopId: res.data.data.shopId,
          userId: res.data.data.userId
        }).then(response =>{
          if(response.data.success){
            that.setData({
            shopName :response.data.data.shopName,
  
            })    
          }
        })
        
      })
     
    }
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId 
    //     api.post('user/getWxOpenId',{
    //         code: res.code,
    //         shopId: app.globalData.shopId
    //     }).then(response =>{
    //       that.setData({
    //         mobileGrant:response.data.data.mobileGrant
    //       })
    //       if(response.data.data.mobileGrant === 0){
    //         that.getUserDetal(response.data.data.userId)
    //         that.setData({
    //           phone: response.data.data.mobile,
    //           conMT: '60rpx'
    //         })
    //       }
    //       api.post('shop/getShop',{
    //         shopId: app.globalData.shopId,
    //         userId: response.data.data.userId
    //       }).then(response =>{
    //         if(response.data.success){
    //           that.setData({
    //           shopName :response.data.data.shopName,

    //           })    
    //         }
    //       })

    //     })

    //   }
    // })

    api.post('shop/getPayChannel', {
      shopId: app.globalData.shopId
    }).then(res => {
      if (res.data.data === 1) {
        that.setData({
          isYLPay: true
        })
      }
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          leftOffset: res.windowWidth / 2 - 100 + 'px'
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          wx.showLoading({
            title: '无网络连接'
          })
          that.setData({
            noNet: true
          })
        }
      }
    })

    this.setData({
      phone: wx.getStorageSync('phone'),
      minAmount: wx.getStorageSync('minAmount'),
      maxAmount: wx.getStorageSync('maxAmount'),
      couponDiscount: wx.getStorageSync('couponDiscount'),
      voucherId: wx.getStorageSync('coupId'),
      disType: wx.getStorageSync('disType')
    })
    if (this.data.userId || wx.getStorageSync('user').userId) {
      this.getUserDetal()
    }

    if (this.data.couponDiscount && this.data.disType === '01') {
      var payamount = Math.floor(this.data.amount * this.data.couponDiscount * 10) / 100
      var zk = ((this.data.amount * 100 - payamount * 100) / 100).toFixed(2)
      if (parseInt(100 * this.data.amount) && payamount >= 0 && payamount <= 0.01) {
        payamount = 0.01;
        zk = (this.data.amount - 0.01).toFixed(2)
      }

      // 满足最大优惠条件时候
      if ((this.data.maxAmount || this.data.maxAmount === "0") && zk >= parseInt(this.data.maxAmount)) {
        zk = this.data.maxAmount;
        payamount = this.data.amount - this.data.maxAmount;
      }

      this.setData({
        discountMoney: zk,
        needPay: payamount
      })

    } else if (this.data.couponDiscount && this.data.disType === '00') {
      // 抵扣券
      var zk = this.data.couponDiscount / 1000;
      var payamount = (this.data.amount - zk).toFixed(2);
      if (zk >= this.data.amount) {
        payamount = 0.01;
        zk = (this.data.amount - 0.01).toFixed(2)
      }
      this.setData({
        discountMoney: zk,
        needPay: payamount
      })
    } else {
      if (this.data.userId) {
        this.handleMydiscount()
      }

    }
  },
  /* 手机号授权并注册登录 */
  getPhoneNumber: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    api.post('user/decrypt', {
      sessionKey: encodeURIComponent(wx.getStorageSync('user').session_key),
      encryptedData: encodeURIComponent(e.detail.encryptedData),
      iv: encodeURIComponent(e.detail.iv)
    }).then(res => {
      if (res.data.success) {
        that.setData({
          phone: res.data.data.phoneNumber
        })
        wx.setStorageSync('phone', res.data.data.phoneNumber);
        // 注册登录 
        api.post('user/getByMobile', {
          mobile: res.data.data.phoneNumber,
          openid: wx.getStorageSync('user').openid,
          shopId: app.globalData.shopId,
        }).then(response => {
          // 获取用户信息
          if (response.data.success) {
            that.setData({
              balance: response.data.data.totalBalance / 100 || 0,
              userId: response.data.data.userId,
              couponNumber: 0,
              userLevelName: response.data.data.userLevelName, // 会员等级中文
              discount: response.data.data.discount, // 折扣
              vipDiscount: response.data.data.discount,
              'radioItems[0].name': '余额支付(剩余' + response.data.data.totalBalance / 100 + '元)',
              wxCard: response.data.data.wxCard,
              conMT: '60rpx'
            })
            if (response.data.data.mobile === 0) {
              that.setData({
                'radioItems[1].checked': true,
                isWePay: true,
                'radioItems[0].checked': false
              })
            } else {
              that.setData({
                'radioItems[0].checked': true,
                isWePay: false,
                'radioItems[1].checked': false
              })
            }
          }
          that.getCouponNo(0)
        })
        wx.hideLoading()

      }
      wx.hideLoading()
    })
  },
  /* 显示文本框 */
  showMsg: function () {
    this.setData({
      showTexarea: !this.data.showTexarea
    })
  },
  /* 选择支付方式 */
  radioChange: function (e) {
    if (e.detail.value === '1') {
      this.setData({
        isWePay: true
      })
    } else {
      this.setData({
        isWePay: false
      })
    }
    var radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
      radioItems: radioItems
    });
  },
  /* 设置附着键盘 */
  handelFixedBtn: function (e) {
    this.setData({
      fixedBtnHeight: e.detail.height + 'px'
    })
  },
  /* 失焦获取金额 */
  getAmount: function (e) {
    this.setData({
      fixedBtnHeight: 0 + 'px',
      amount: e.detail.value
    })
  },
  /* 失焦获取备注 */
  getRemark: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  /* 输入时获取留言长度 */
  getLength: function (e) {
    this.setData({
      remarkLength: e.detail.value.length
    })
  },
  /* 输入时候校验 */
  handelCheck: function (e) {
    var that = this

    e.detail.value = e.detail.value.replace(/\-/g, "")
    e.detail.value = e.detail.value.replace(/\.{2,}/g, ".")
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (e.detail.value.indexOf('.') == 0) { //第一位就是 .
      e.detail.value = '0' + e.detail.value
    }
    var zk, payamount
    if (this.data.couponDiscount && this.data.disType === '01') {
      payamount = Math.floor(e.detail.value * this.data.couponDiscount * 10) / 100
      if (this.data.minAmount && e.detail.value < this.data.minAmount) {
        wx.showToast({
          title: MSG.ERR_NOT_COUPON,
          icon: 'none',
          duration: 1500
        })
        return this.handleMydiscount(e.detail.value)
      }
      zk = ((e.detail.value * 100 - payamount * 100) / 100).toFixed(2)
    } else if (this.data.couponDiscount && this.data.disType === '00') {
      // 折扣券
      zk = this.data.couponDiscount / 1000;
      payamount = (e.detail.value - zk).toFixed(2);
      if (zk >= e.detail.value) {
        payamount = 0.01;
        zk = (e.detail.value - 0.01).toFixed(2)
      }
    } else {
      payamount = Math.floor(e.detail.value * this.data.discount * 10) / 100
      zk = ((e.detail.value * 100 - payamount * 100) / 100).toFixed(2)
    }


    // 满足最大优惠条件时候
    if (this.data.maxAmount && zk >= this.data.maxAmount) {
      zk = this.data.maxAmount;
      payamount = e.detail.value - this.data.maxAmount;
    }

    if (parseInt(100 * e.detail.value) && payamount >= 0 && payamount <= 0.01) {
      payamount = 0.01;
      zk = (e.detail.value - 0.01).toFixed(2)
    }

    // 获取可用优惠券
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(function () {
      timeout = null;
      that.getCouponNo(e.detail.value)
    }, 1000)
    this.setData({
      amount: e.detail.value,
      discountMoney: zk,
      needPay: payamount
    })
  },
  /* 获取用户信息 */
  getUserDetal: function (id) {
    var that = this

    api.post('user/getUserInfo', {
      userId: id || wx.getStorageSync('user').userId,
      shopId: app.globalData.shopId,
    }).then(response => {
      // 获取用户信息
      if (response.data.success) {
        that.setData({
          balance: response.data.data.totalBalance / 100,
          userId: response.data.data.userId,
          mobileGrant: response.data.data.mobileGrant,
          userLevelName: response.data.data.userLevelName, // 会员等级中文
          discount: response.data.data.discount, // 折扣
          vipDiscount: response.data.data.discount,
          'radioItems[0].name': '余额支付(剩余' + response.data.data.totalBalance / 100 + '元)',
          wxCard: response.data.data.wxCard,
          conMT: '60rpx'
        })
        if(response.data.data.mobileGrant===1 && !response.data.data.mobile ){
          that.setData({
            conMT: '440rpx'
          })
        }
        if (response.data.data.totalBalance === 0 || response.data.data.mobile === 0) {
          that.setData({
            'radioItems[1].checked': true,
            isWePay: true,
            'radioItems[0].checked': false
          })
        } else {
          that.setData({
            'radioItems[0].checked': true,
            isWePay: false,
            'radioItems[1].checked': false
          })
        }
        that.getCouponNo(that.data.amount)
      }

    })
  },
  /* 没有手机号以及unionid */
  handleUsePage: function () {
    wx.showToast({
      title: '授权微信和手机号',
      icon: 'none',
      duration: 1500
    })
    setTimeout(function () {
      wx.navigateTo({
        url: '/pages/user/index'
      })
    }, 1500)
  },
  /* 验证码输入 */
  Tap() {
    var that = this;
    that.setData({
      isFocus: true,
    })
  },
  Focus(e) {
    var that = this;
    var inputValue = e.detail.value;
    that.setData({
      Value: inputValue,
    })

    if (this.data.Value.length === 4) {
      this.smsPay()
    }
  },
  /* 获取优惠券张数 */
  getCouponNo: function (pAmount) {
    var that = this
    wx.showLoading({
      title: '加载中'
    })
    setTimeout(function () {
      api.post('funds/user/voucher/list', {
        page: 1,
        pageSize: 10,
        userId: that.data.userId + '',
        status: "00",
        shopId: app.globalData.shopId + '',
        payAmount: pAmount * 100
      }).then(res => {
        if (res.data.success) {
          that.setData({
            couponNumber: res.data.data.total
          })
        }
        wx.hideLoading()
      })
    }, 500)

  },
  /* 选择 会员卡优惠*/
  handleMydiscount: function (money) {
    var that = this
    var payamount = Math.floor(this.data.amount * this.data.vipDiscount * 10) / 100
    var zk = ((this.data.amount * 100 - payamount * 100) / 100).toFixed(2)
    wx.setStorageSync('couponDiscount', '');
    wx.setStorageSync('minAmount', '');
    wx.setStorageSync('maxAmount', '');
    if (parseInt(100 * this.data.amount) && payamount >= 0 && payamount <= 0.01) {
      payamount = 0.01;
      zk = (this.data.amount - 0.01).toFixed(2)
    }
    if (parseFloat(money)) {
      payamount = Math.floor(money * this.data.vipDiscount * 10) / 100
      zk = ((money * 100 - payamount * 100) / 100).toFixed(2)
      this.getCouponNo(money)
    }
    this.getCouponNo(this.data.amount)

    this.setData({
      choseCard: true,
      discountMoney: zk,
      needPay: payamount,
      voucherId: '',
      minAmount: '',
      couponDiscount: '',
      maxAmount: ''

    })
  },
  /* 选择 优惠券 */
  handleMyCoupon: function () {
    if (!parseFloat(this.data.amount) != 0) {
      return wx.showToast({
        title: MSG.ERR_AMOUNT_IS_EMPTY,
        icon: 'none',
        duration: 1500
      })
    }
    this.setData({
      choseCard: false,
      discountMoney: ''
    })

    wx.navigateTo({
      url: '/pages/usingCoupon/index?userId=' + this.data.userId + '&payAmount=' + this.data.amount
    })
  },
  /* 发送验证码 */
  getSmsCode: function () {
    this.setData({
      smsConfirm: true
    })
    wx.showLoading({
      title: '验证码发送中',
    })
    api.post('user/getVerificationCode', {
      mobile: this.data.phone,
      type: 1
    }).then(res => {
      wx.hideLoading()
      if (res.data.success) {
        return
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1500
        })
        this.setData({
          smsConfirm: false
        })
      }
    })
  },
  /* 立即支付 */
  payNow: function (event) {
    var that = this
    this.setData({
      Value: ''
    })
    if (!this.data.amount) {
      return wx.showToast({
        title: MSG.ERR_AMOUNT_IS_EMPTY,
        icon: 'none',
        duration: 1500
      })
    }
    if (parseFloat(this.data.amount) === 0.00) {
      return wx.showToast({
        title: '订单金额不能为０',
        icon: 'none',
        duration: 1500
      })
    }
    if (this.data.isWePay) {
      this.getWxPay()
    } else {
      if (this.data.needPay > this.data.balance) {
        return wx.showModal({
          content: MSG.ERR_BALANCE_NOT_ENOUGH,
          cancelColor: '#ddd',
          confirmText: '充值',
          confirmColor: '#6c53f2',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/balance/index?userId=' + that.data.userId + '&balance=' + that.data.balance
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
      this.getSmsCode()
    }
    // 保存formID

    let formId = event.detail.formId;
    // 忽略开发者工具里边的formId
    if (formId && formId !== 'the formId is a mock one') {
      that.saveFormId(formId)
      console.log('formId:' + formId)
    }


  },
  /* 余额支付 */
  smsPay: function () {
    var that = this;

    wx.showLoading({
      title: '支付中',
    })
    api.post('funds/user/account/smspay', {
      amount: parseInt((this.data.needPay * 100).toFixed(0)),
      mobile: this.data.phone,
      reduceAmount: parseInt((this.data.discountMoney * 100).toFixed(0)),
      shopId: app.globalData.shopId + '',
      smscode: this.data.Value,
      totalAmount: parseInt((this.data.amount * 100).toFixed(0)),
      userId: this.data.userId + '',
      voucherId: this.data.voucherId,
      remark: this.data.remark
    }).then(res => {
      wx.hideLoading()
      if (res.data.success) {
        wx.redirectTo({
          url: '/pages/paysuccess/index?needPay=' + that.data.needPay
        })
      } else {
        that.closeSms()
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1500
        })
      }
      console.log(res)

    })
  },
  /* 关闭短信 */
  closeSms: function () {
    this.setData({
      smsConfirm: false
    })
  },
  /* 调用微信支付 */
  getWxPay: function () {
    var that = this
    if (that.data.isYLPay) {
      api.post('funds/user/account/unionpay', {
        amount: parseInt((this.data.needPay * 100).toFixed(0)),
        openId: wx.getStorageSync('user').openid,
        reduceAmount: parseInt((this.data.discountMoney * 100).toFixed(0)),
        shopId: app.globalData.shopId + '',
        totalAmount: parseInt((this.data.amount * 100).toFixed(0)),
        userId: this.data.userId + '',
        voucherId: this.data.voucherId,
        remark: this.data.remark
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp + '',
            nonceStr: res.data.data.nonceStr + '',
            package: res.data.data.package + '',
            signType: res.data.data.signType + '',
            paySign: res.data.data.paySign + '',
            success: function (res) {
              if (that.data.wxCard) {

                setTimeout(function () {
                  wx.reLaunch({
                    url: '/pages/user/index'
                  })
                }, 200)
              } else {
                // that.clickMyCard()
                that.openCard()
              }

            },
            fail: function (res) {
              console.log(res)
            },

          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1500
          })
        }

      })
    } else {
      api.post('funds/user/account/wechatsmspay', {
        amount: parseInt((this.data.needPay * 100).toFixed(0)),
        openId: wx.getStorageSync('user').openid,
        reduceAmount: parseInt((this.data.discountMoney * 100).toFixed(0)),
        shopId: app.globalData.shopId + '',
        totalAmount: parseInt((this.data.amount * 100).toFixed(0)),
        userId: this.data.userId + '',
        voucherId: this.data.voucherId,
        remark: this.data.remark
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp + '',
            nonceStr: res.data.data.nonceStr + '',
            package: res.data.data.package + '',
            signType: res.data.data.signType + '',
            paySign: res.data.data.paySign + '',
            success: function (res) {
              if (that.data.wxCard) {

                setTimeout(function () {
                  wx.reLaunch({
                    url: '/pages/user/index'
                  })
                }, 200)
              } else {
                // that.clickMyCard()
                that.openCard()
              }

            },
            fail: function (res) {
              console.log(res)
            },

          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1500
          })
        }

      })
    }
  },
  // 领取会员卡
  clickMyCard: function () {
    var that = this
    wx.request({
      url: api.baseUrl + 'user/getSignature',
      method: 'POST',
      data: {
        cardId: app.globalData.cardId,
        shopId: app.globalData.shopId
      },
      success: function (res) {
        var cardExt = {}
        cardExt.nonce_str = res.data.data.noncestr
        cardExt.timestamp = res.data.data.timestamp
        cardExt.signature = res.data.data.signature
        wx.addCard({
          cardList: [{
            cardId: app.globalData.cardId,
            cardExt: JSON.stringify(cardExt)
          }],
          success(res) {
            that.getCardNo(res.cardList[0].code)
          },
          complete: function (res) {
            setTimeout(function () {
              wx.reLaunch({
                url: '/pages/user/index'
              })
            }, 200)
          }
        })

      },
      fail: function (err) {
        console.log(err)
      }
    })
  },
  /* 解密卡号 */
  getCardNo: function (cardCode) {
    var that = this
    api.post('user/saveCardNum', {
      code: cardCode,
      mobile: wx.getStorageSync('phone'),
      shopId: app.globalData.shopId,
    }).then(res => {

    })
  },
  /* 获取formID */
  clickFormView: function (e) {
    var that = this
    let formId = e.detail.formId;
    // 忽略开发者工具里边的formId
    if (formId && formId !== 'the formId is a mock one') {
      console.log('formId:' + formId)

      this.setData({
        payFormId: formId
      })
      if (!that.data.wxCard) {
        this.saveFormId(formId)
      }

    }
  },
  /* 保存formID */
  saveFormId: function (id) {
    api.post('user/saveFormid', {
      openid: wx.getStorageSync('user').openid,
      shopId: app.globalData.shopId,
      formid: id
    }).then(res => {
      console.log(res)
    })
  },
  /* 跳转首页 */
  goIndex: function () {
    wx.redirectTo({
      url: '/pages/user/index'
    })
  },
  /* 开卡组件 */
  openCard: function () {
    api.post('shop/getCardActivate', {
      shopId: app.globalData.shopId,
    }).then(res => {
      console.log(res)
      let obj = {}
      obj['biz'] = decodeURIComponent(res.data.data.biz);
      obj['encrypt_card_id'] = decodeURIComponent(res.data.data.encrypt_card_id);
      obj['outer_str'] = decodeURIComponent(res.data.data.outer_str)
      wx.navigateToMiniProgram({
        appId: 'wxeb490c6f9b154ef9', //固定为此 appid，不可改动
        extraData: res.data.data, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
        success: function (res) {
          console.log(res, 11)
        },
        fail: function (res) {
          console.log(res)
        },
        complete: function (res) {
          setTimeout(function () {
            wx.reLaunch({
              url: '/pages/user/index'
            })
          }, 200)
        }
      })
    })

  }
})